package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CancelNusingTaskDTO;
import com.zzyl.nursing.dto.DoNursingTaskDTO;
import com.zzyl.nursing.dto.NursingTaskDTO;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.NursingTaskDetailVO;
import com.zzyl.nursing.vo.NursingTaskVO;
import com.zzyl.serve.domain.NursingLevel;
import com.zzyl.serve.domain.NursingProject;
import com.zzyl.serve.mapper.NursingProjectPlanMapper;
import com.zzyl.serve.service.INursingLevelService;
import com.zzyl.serve.service.INursingPlanService;
import com.zzyl.serve.service.INursingProjectService;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 *
 * @author mr.luo
 * @date 2025-06-01
 */
@Slf4j
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private IElderService iElderService;
    @Autowired
    private NursingProjectPlanMapper NursingProjectPlanMapper;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskDetailVO selectNursingTaskById(Long id) {
        NursingTask nursingTask = this.getById(id);
        NursingTaskDetailVO nursingTaskDetailVO = new NursingTaskDetailVO();
        BeanUtils.copyProperties(nursingTask, nursingTaskDetailVO);
        log.info("查询结果：{}", nursingTaskDetailVO);
        //封装一些 属性值
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        nursingTaskDetailVO.setCreateTime(nursingTask.getCreateTime()
                .format(dateTimeFormatter));
        nursingTaskDetailVO.setEstimatedServerTime(nursingTask.getEstimatedServerTime().format(dateTimeFormatter));
        nursingTaskDetailVO.setId(nursingTask.getId().intValue());

        //查询老人的护理等级与性别
        Long elderId = nursingTask.getElderId();
        Long projectId = nursingTask.getProjectId();
        NursingLevel nursingLevel = NursingProjectPlanMapper.getProjectPlanName(projectId);
        nursingTaskDetailVO.setNursingLevelName(nursingLevel.getName());
        Elder one = iElderService.lambdaQuery().select(Elder::getSex, Elder::getAge).eq(Elder::getId, elderId).one();
        nursingTaskDetailVO.setSex(one.getSex());
        nursingTaskDetailVO.setAge(one.getAge());
        nursingTaskDetailVO.setElderId(elderId.intValue());

//        ---------------------------------------------------------------
        List<Integer> setNursingName = new ArrayList<>();
        String nursingId = nursingTask.getNursingId();
        getNursingName(nursingId, setNursingName);
        List<Integer> collect = setNursingName.stream().distinct().collect(Collectors.toList());
        //查找护理人员名称
        // 检查 collect 是否为空
        List<SysUser> sysUsers;
        if (!collect.isEmpty()) {
            sysUsers = isSysUserService.listByIds(collect);
        } else {
            sysUsers = new ArrayList<>();
        }
        List<String> collect1 = sysUsers.stream().map(SysUser::getNickName).collect(Collectors.toList());
        nursingTaskDetailVO.setNursingName(collect1);
//        -------------------------------------------------------------

        nursingTaskDetailVO.setProjectId(nursingTask.getProjectId().intValue());
        if (nursingTask.getRealServerTime() != null) {
            nursingTaskDetailVO.setRealServerTime(nursingTask.getRealServerTime().format(dateTimeFormatter));
        }
        String username = SecurityUtils.getLoginUser().getUsername();
        if (nursingTask.getStatus() == 3) {
            nursingTaskDetailVO.setUpdateTime(nursingTask.getUpdateTime().format(dateTimeFormatter));
            nursingTaskDetailVO.setUpdater(username);
        }

        if (nursingTask.getStatus() == 2) {
            //TODO
            nursingTaskDetailVO.setUpdateTime(nursingTask.getUpdateTime().format(dateTimeFormatter));
            nursingTaskDetailVO.setUpdater(username);
        }
        //设置创建人
        Integer createById = Integer.valueOf(nursingTask.getCreateBy());
        SysUser sysUser = isSysUserService.getById(createById);
        nursingTaskDetailVO.setCreateBy(sysUser.getUserName());
        return nursingTaskDetailVO;
    }

    @Autowired
    private ISysUserService isSysUserService;

    /**
     * 查询护理任务列表
     *
     * @param nursingTaskDTO 护理任务
     * @return 护理任务
     */
    @Override
    public Page<NursingTaskVO> selectNursingTaskList(NursingTaskDTO nursingTaskDTO) {
        Page<NursingTask> page = new Page<>(nursingTaskDTO.getPageNum(), nursingTaskDTO.getPageSize());
        this.lambdaQuery()
                .like(StrUtil.isNotBlank(nursingTaskDTO.getElderName()), NursingTask::getElderName, nursingTaskDTO.getElderName())
                .like(nursingTaskDTO.getNurseId() != null, NursingTask::getNursingId, nursingTaskDTO.getNurseId())
                .eq(nursingTaskDTO.getProjectId() != null, NursingTask::getProjectId, nursingTaskDTO.getProjectId())
                .eq(nursingTaskDTO.getStatus() != null, NursingTask::getStatus, nursingTaskDTO.getStatus())
                .between(nursingTaskDTO.getStartTime() != null && nursingTaskDTO.getEndTime() != null,
                        NursingTask::getCreateTime, nursingTaskDTO.getStartTime(), nursingTaskDTO.getEndTime())
                .orderByDesc(NursingTask::getCreateTime)
                .page(page);

        List<NursingTask> records = page.getRecords();
        List<Integer> nursingIds = new ArrayList<>();
        records.forEach(s -> {
            String nursingId = s.getNursingId();
            getNursingName(nursingId, nursingIds);
        });
        log.info("nursingIds:{}", nursingIds);
        List<Integer> collect = nursingIds.stream().distinct().collect(Collectors.toList());

        // 检查 collect 是否为空
        List<SysUser> sysUsers;
        if (!collect.isEmpty()) {
            sysUsers = isSysUserService.listByIds(collect);
        } else {
            sysUsers = new ArrayList<>();
        }

        List<NursingTaskVO> collect1 = records.stream().map(nursingTask -> {
            NursingTaskVO nursingTaskVO = new NursingTaskVO();
            BeanUtils.copyProperties(nursingTask, nursingTaskVO);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            nursingTaskVO.setCreateTime(nursingTask.getCreateTime().format(dateTimeFormatter));
            nursingTaskVO.setEstimatedServerTime(nursingTask.getEstimatedServerTime().format(dateTimeFormatter));

            nursingTaskVO.setId(nursingTask.getId().intValue());
            nursingTaskVO.setProjectId(nursingTask.getProjectId().intValue());
            nursingTaskVO.setElderId(nursingTask.getElderId().intValue());
            nursingTaskVO.setNursingId(nursingTask.getNursingId());
            sysUsers.forEach(sysUser -> {
                if (nursingTask.getNursingId().contains(sysUser.getUserId().toString())) {
                    nursingTaskVO.getNursingName().add(sysUser.getNickName());
                }
            });
            return nursingTaskVO;
        }).collect(Collectors.toList());

        Page<NursingTaskVO> page2 = new Page<>();
        page2.setTotal(page.getTotal());
        page2.setRecords(collect1);
        return page2;
    }

    private static void getNursingName(String nursingId, List<Integer> nursingIds) {
        if (nursingId.contains(",")) {
            String[] split = nursingId.split(",");
            List<Integer> collect1 = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
            nursingIds.addAll(collect1);
        } else {
            nursingIds.add(Integer.parseInt(nursingId));
        }
    }

    /**
     * 取消任务
     *
     * @param cancelNusingTaskDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(CancelNusingTaskDTO cancelNusingTaskDTO) {
        boolean update = lambdaUpdate().eq(NursingTask::getId, cancelNusingTaskDTO.getTaskId())
                .set(NursingTask::getStatus, 3)
                .set(NursingTask::getCancelReason, cancelNusingTaskDTO.getReason())
                .set(NursingTask::getUpdateTime, LocalDateTime.now())
                .set(NursingTask::getUpdateBy, SecurityUtils.getLoginUser().getUserId())
                .update();
        if (!update) {
            throw new BaseException("更新数据失败");
        }

    }

    /**
     * 执行任务
     *
     * @param doNursingTaskDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void execute(DoNursingTaskDTO doNursingTaskDTO) {
        boolean update = lambdaUpdate().eq(NursingTask::getId, doNursingTaskDTO.getTaskId())
                .set(NursingTask::getStatus, 2)
                .set(NursingTask::getRealServerTime, LocalDateTime.now())
                .set(NursingTask::getEstimatedServerTime, doNursingTaskDTO.getEstimatedServerTime())
                .set(NursingTask::getTaskImage, doNursingTaskDTO.getTaskImage())
                .set(NursingTask::getUpdateTime, LocalDateTime.now())
                .set(NursingTask::getUpdateBy, SecurityUtils.getLoginUser().getUserId())
                .set(NursingTask::getMark, doNursingTaskDTO.getMark())
                .update();
        if (!update) {
            throw new BaseException("更新数据失败");
        }
    }

    /**
     * 任务改期
     *
     * @param doNursingTaskDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void change(DoNursingTaskDTO doNursingTaskDTO) {
        //先判断任务状态是否为1
        NursingTask nursingTask = lambdaQuery().eq(NursingTask::getId, doNursingTaskDTO.getTaskId()).one();
        if (nursingTask.getStatus() != 1) {
            throw new BaseException("任务状态异常，无法更改");
        }
        nursingTask.setEstimatedServerTime(LocalDateTime.parse(doNursingTaskDTO.getEstimatedServerTime()
                , DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean update = updateById(nursingTask);
        if (!update) {
            throw new BaseException("更新数据失败");
        }

    }

    @Autowired
    private ICheckInService checkInService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private INursingLevelService nursingLevelService;
    @Autowired
    private INursingPlanService nursingPlanService;
    @Autowired
    private INursingElderService nursingElderService;
    @Autowired
    private INursingProjectService nursingProjectService;

    /**
     * 生成月任务
     * 就是根据老人的 生信息，生成月任务
     * 往本表中插入数据
     *
     * @param elder
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateMonthlyTask(Elder elder) {
        //首先先判断老人是不是空的
        if (elder == null || elder.getId() == null) {
            log.error("老人信息为空");
            return;
        }
        // 基础校验2：根据传进来的老人的id，获取入住的信息
        CheckIn checkIn = checkInService.lambdaQuery().eq(CheckIn::getElderId, elder.getId()).one();
        if (ObjectUtil.isEmpty(checkIn)) {
            log.error("入住信息不能为空");
            return;
        }
        // 基础校验3：根据上面查询的入住信息获取入住配置信息
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        if (ObjectUtil.isEmpty(checkInConfig)) {
            log.error("入住配置不能为空");
            return;
        }
        // 基础校验4：根据上面查询的入住配置信息中的护理等级id，查询护理等级信息
        NursingLevel nursingLevel = nursingLevelService.selectNursingLevelById(checkInConfig.getNursingLevelId());
        if (ObjectUtil.isEmpty(nursingLevel)) {
            log.error("护理等级不能为空");
            return;
        }
        // 基础校验5：根据上面查询的护理等级信息中的护理计划id，查询查询护理计划信息
        NursingPlanVo nursingPlanVo = nursingPlanService.selectNursingPlanById(nursingLevel.getLplanId());
        if (ObjectUtil.isEmpty(nursingPlanVo)) {
            log.error("护理计划不能为空");
            return;
        }

        // 基础校验6：获取上面查询到的护理计划VO，获取护理计划和项目关联的信息（计划id，计划执行时间，执行周期与执行频次）
        List<NursingProjectPlanVo> projectPlans = nursingPlanVo.getProjectPlans();
        if (CollUtil.isEmpty(projectPlans)) {
            log.error("护理计划项目计划列表不能为空");
            return;
        }
        // 基础校验7：查询老人与护理人之间的关系表，查询出老人id与护理员id
        List<NursingElder> nursingElderList = nursingElderService
                .lambdaQuery()
                .eq(NursingElder::getElderId, elder.getId())
                .list();
        if (CollUtil.isEmpty(nursingElderList)) {
            log.error("护理人员不能为空");
            return;
        }
        // 8.将上面包含老人id与 护护员id的列表，过滤成只有 护护员id的列表
        List<Long> list = nursingElderList.stream()
                .map(NursingElder::getNursingId).collect(Collectors.toList());
        // 将所有护理员的id转换成用逗号分隔的字符串
        String nursingIds = StringUtils.join(list, ",");
        // 查询所有的护理项目
        List<NursingProject> projectList = nursingProjectService.list();
        // 将所有的护理项目 转换成Map 键是id 值是name
        Map<Long, String> nursingProjectMap = projectList.stream()
                .collect(Collectors.toMap(NursingProject::getId, NursingProject::getName));
        // 开始时间
        LocalDateTime finalStartTime = LocalDateTime.now();
        // 开始组装护理任务
        List<NursingTask> nursingTasks = new ArrayList<>();
        //遍历护理计划
        projectPlans.forEach(planVo -> {
            // 获取执行频次
            Integer executeFrequency = Integer.valueOf(planVo.getExecuteFrequency());
            // 获取执行时间
            String executeTime = planVo.getExecuteTime();
            //保存的只有时分秒，使用 LocalTime
            LocalTime localTime = LocalTime.parse(executeTime);
            // 开始执行时间（拼接时间，获取今天的date然后与执行时间的dateTime进行拼接，组成localDateTime类型的）
            LocalDateTime firstExecutionTime = LocalDateTime.of(finalStartTime.toLocalDate(), localTime);
            // 计算相差天数 获取当前的年份，开始付费的月份，以及当前月份的最后一天的23时59秒
            LocalDateTime monthEndTime = LocalDateTime.of(finalStartTime.getYear(), checkInConfig.getFeeStartDate().getMonth(),
                    finalStartTime.toLocalDate().lengthOfMonth(), 23, 59);
            // 间隔天数
            //long diffDays = monthEndTime.toLocalDate().toEpochDay() - finalStartTime.toLocalDate().toEpochDay() + 1;
            //TODO 计算出当前时间与开始付费时间那一月的最后一天的最后一秒的相差的天数  计算两个 LocalDateTime 时间之间的天数差，并取绝对值。
            long diffDays = Math.abs(LocalDateTimeUtil.between(finalStartTime, monthEndTime, ChronoUnit.DAYS));
            //判断护理计划中的执行周期是日、周、月
            if ("0".equals(planVo.getExecuteCycle())) {
                // 日   传进去的方法形参：开始执行时间、当前时间与开始缴费月的最后一天的时间差，
                // 组装护理任务的空集合，护理计划的执行频次、老人对象，项目计划关系对象，护理员的id字符串，所有护理项目的键值对
                generateTaskByDay(firstExecutionTime, diffDays, nursingTasks, executeFrequency,
                        elder, planVo, nursingIds, nursingProjectMap);
            } else if ("1".equals(planVo.getExecuteCycle())) {
                // 周
                generateTaskByWeek(firstExecutionTime, diffDays, nursingTasks, executeFrequency,
                        elder, planVo, monthEndTime, nursingIds, nursingProjectMap);
            } else {
                // 月
                generateTaskByMonth(firstExecutionTime, monthEndTime, nursingTasks, executeFrequency,
                        elder, planVo, nursingIds, nursingProjectMap);
            }
        });
        this.saveBatch(nursingTasks);
    }

    /**
     * 按月创建任务
     *
     * @param firstExecutionTime
     * @param monthEndTime
     * @param nursingTasks
     * @param executeFrequency
     * @param elder
     * @param v
     */
    private void generateTaskByMonth(LocalDateTime firstExecutionTime, LocalDateTime monthEndTime, List<NursingTask> nursingTasks, Integer executeFrequency, Elder elder, NursingProjectPlanVo v, String nursingIds, Map<Long, String> nursingProjectMap) {
        LocalDateTime executionTime = firstExecutionTime;
        Integer diffDay = (monthEndTime.plusSeconds(1).getDayOfMonth() - executionTime.getDayOfMonth()) / executeFrequency;
        for (int x = 0; x < executeFrequency; x++) {
            // 根据时间差和执行顺序计算每个任务的具体时间
            LocalDateTime seconds = executionTime.plusDays(diffDay * x);
            // 初始化护理任务对象
            NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
            // 将生成的任务添加到任务列表中
            nursingTasks.add(nursingTask);
        }
    }

    /**
     * 根据周为单位创建护理任务
     * <p>
     * 此方法旨在根据给定的开始时间、差异天数、执行频率等参数，为指定的老人生成护理任务列表
     * 它考虑了跨年情况以及每月结束时间的限制，避免生成越过月末的有效任务
     *
     * @param firstExecutionTime 首次执行时间，用于计算后续任务的时间点
     * @param diffDays           任务之间的时间差，以天为单位，此方法专注于周级别，故此值应与7的倍数有关
     * @param nursingTasks       护理任务列表，方法将新生成的任务添加到此列表中
     * @param executeFrequency   执行频率，决定每周内任务执行的次数
     * @param elder              老人信息对象，任务相关的老人信息由此对象提供
     * @param v                  护理项目计划的视图对象，包含项目ID等信息
     * @param monthEndTime       每月结束时间的限制，确保任务不会跨月生成
     * @param nursingIds         护理员ID列表，以字符串形式传递，用于分配任务给护理员
     */
    private void generateTaskByWeek(LocalDateTime firstExecutionTime, long diffDays, List<NursingTask> nursingTasks, Integer executeFrequency, Elder elder, NursingProjectPlanVo v, LocalDateTime monthEndTime, String nursingIds, Map<Long, String> nursingProjectMap) {
        int i;
        // 以7天为步长遍历差异天数，创建每周的任务
        for (i = 0; i < diffDays - 7; i = i + 7) {
            // 计算每周结束时间
            LocalDateTime dayEndTime = LocalDateTime.of(firstExecutionTime.plusDays(i + 7).toLocalDate(), LocalTime.of(23, 59));
            // 计算本周的执行起始时间
            LocalDateTime executionTime = firstExecutionTime.plusDays(i);
            // 根据执行频率计算时间差，用于确定本周内各任务的时间点
            Integer diffDay = (dayEndTime.plusSeconds(1).getDayOfYear() - executionTime.getDayOfYear()) / executeFrequency;
            // 根据执行频率生成本周的任务
            for (int x = 0; x < executeFrequency; x++) {
                // 根据时间差和执行顺序计算每个任务的具体时间
                LocalDateTime seconds = executionTime.plusDays(diffDay * x);
                // 初始化护理任务对象
                NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
                // 将生成的任务添加到任务列表中
                nursingTasks.add(nursingTask);
            }
        }

        // 处理边界情况，当i超过diffDays-7且小于diffDays时
        if (i > diffDays - 7 && i < diffDays) {
            // 计算到达diffDays时的结束时间
            LocalDateTime dayEndTime = LocalDateTime.of(firstExecutionTime.plusDays(i + 7).toLocalDate(), LocalTime.of(23, 59));
            // 如果结束时间与开始时间年份不同，则返回，避免跨年任务
            if (ObjectUtil.notEqual(dayEndTime.getYear(), firstExecutionTime.getYear())) {
                return;
            }
            // 计算执行时间
            LocalDateTime executionTime = firstExecutionTime.plusDays(i);
            // 计算时间差，确定任务时间点
            Integer diffDay = (dayEndTime.plusSeconds(1).getDayOfYear() - executionTime.getDayOfYear()) / executeFrequency;
            // 根据执行频率生成任务，直到月末
            for (int x = 0; x < executeFrequency; x++) {
                // 计算每个任务的时间
                LocalDateTime seconds = executionTime.plusDays(diffDay * x);
                // 如果任务时间超过月末结束时间，则停止生成
                if (seconds.isAfter(monthEndTime)) {
                    break;
                }
                // 初始化护理任务对象
                NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
                // 将生成的任务添加到任务列表中
                nursingTasks.add(nursingTask);
            }
        }

    }

/**
 * 按日创建任务
 * @param firstExecutionTime
 * @param diffDays
 * @param nursingTasks
 * @param executeFrequency
 * @param elder
 * @param v
 */
    /**
     * 根据天数创建护理任务
     * <p>
     * 该方法根据首次执行时间、任务间隔天数、护理任务列表、执行频率、老人信息和护理项目计划数据，
     * 创建一系列的护理任务。任务的创建以天为单位，直到达到任务间隔天数为止。
     *
     * @param firstExecutionTime 首次执行时间，标志着任务创建的起始时间
     * @param diffDays           任务间隔天数，确定需要创建任务的天数范围
     * @param nursingTasks       护理任务列表，创建的任务将被添加到此列表中
     * @param executeFrequency   执行频率，决定一天内任务执行的次数
     * @param elder              老人对象，包含执行任务的老人的信息
     * @param v                  护理项目计划数据对象，包含护理项目的相关信息
     */
    private void generateTaskByDay(LocalDateTime firstExecutionTime, long diffDays,
                                   List<NursingTask> nursingTasks, Integer executeFrequency,
                                   Elder elder, NursingProjectPlanVo v, String nursingIds,
                                   Map<Long, String> nursingProjectMap) {
        // 遍历每一天，从首次执行时间开始，直到达到任务间隔天数
        for (int i = 0; i < diffDays; i++) {
            // 计算每一天的任务执行起始时间
            LocalDateTime executionTime = firstExecutionTime.plusDays(i);
            // 确定当天任务执行的结束时间（当天的23:59）
            LocalDateTime dayEndTime = LocalDateTime.of(executionTime.toLocalDate(), LocalTime.of(23, 59));
            // 计算当天内每次执行任务之间的小时差，用于确定执行时间点
            Integer diffHour = (dayEndTime.plusSeconds(1).getHour() - executionTime.getHour()) / executeFrequency;
            // 根据执行频率创建任务
            for (int x = 0; x < executeFrequency; x++) {
                // 计算每个任务的具体执行时间
                LocalDateTime seconds = executionTime.plusHours(diffHour * x);
                // 创建新的护理任务对象
                NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
                // 将生成的任务添加到任务列表中
                nursingTasks.add(nursingTask);
            }
        }
    }

    /**
     * 获取护理任务对象
     *
     * @param elder
     * @param v
     * @param nursingIds
     * @param seconds
     * @return
     */
    private NursingTask getNursingTask(Elder elder, NursingProjectPlanVo v, String nursingIds, LocalDateTime seconds, Map<Long, String> nursingProjectMap) {
        NursingTask nursingTask = new NursingTask();
        // 设置任务状态
        nursingTask.setStatus(1);
        // 设置护理员ID列表
        nursingTask.setNursingId(nursingIds);
        // 老人姓名
        nursingTask.setElderName(elder.getName());
        // 设置床位号
        nursingTask.setBedNumber(elder.getBedNumber());
        // 设置预估服务时间
        nursingTask.setEstimatedServerTime(seconds);
        // 设置项目ID
        nursingTask.setProjectId(Long.valueOf(v.getProjectId()));
        // 设置老人ID
        nursingTask.setElderId(elder.getId());
        // 匹配护理项目
        nursingTask.setProjectName(nursingProjectMap.get(Long.valueOf(nursingTask.getProjectId())));
        // 设置任务类型
        nursingTask.setTaskType(2);
        //设置createBy
        nursingTask.setCreateBy("1");
        nursingTask.setUpdateBy("1");
        return nursingTask;
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
